package com.company.project.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.project.entity.WorkOrderEntity;
import com.company.project.mapper.WorkOrderMapper;
import com.company.project.service.WorkOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Service("workOrderService")
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrderEntity> implements WorkOrderService {

    @Resource
    WorkOrderMapper workOrderMapper;

    public JSONArray getOrders(String workshop) {
        JSONArray result = new JSONArray();
        String[] machines = machineMap.get(workshop);
        for (String machine : machines) {
            if ("J-1".equals(machine)) {
                this.getOrders4JY(result);
            } else {
                List<WorkOrderEntity> orders = workOrderMapper.findOrderByMachine(machine, 5);
                result.add(this.buildLine(orders, machine, 0, orders.size()));
            }
        }
        return result;
    }

    private void getOrders4JY(JSONArray result) {
        List<WorkOrderEntity> orders = workOrderMapper.findOrderByMachine("J-1", 15);
        result.add(buildLine(orders, "", 0, 5));
        result.add(buildLine(orders, "J-1", 5, 10));
        result.add(buildLine(orders, "", 10, 15));
    }

    private JSONObject buildLine(List<WorkOrderEntity> orders, String machineName, int begin, int end) {
        JSONObject productionPlan = new JSONObject();
        productionPlan.put("machineName", machineName);
        JSONArray ordersMap = new JSONArray();
        end = end > orders.size() ? orders.size() : end;
        for (int i = begin; i < end; i++) {
            WorkOrderEntity order = orders.get(i);
            JSONObject orderMap = new JSONObject();
            orderMap.put("custom", order.getCustom());
            orderMap.put("batchNumber", order.getBatchNumber());
            orderMap.put("specification", order.getSpecification());
            orderMap.put("weight", order.getWeight().toString());
            ordersMap.add(orderMap);
        }
        productionPlan.put("orders", ordersMap);
        return productionPlan;
    }

    public static Map<String, String[]> machineMap = null;

    public WorkOrderServiceImpl() {
        machineMap = new HashMap<>();
        String[] sb1 = {"Q-1", "Q-2", "Q-3", "Q-4", "Q-5"};
        String[] sb2 = {"Q-6", "Q-7", "Q-8", "Q-9", "Q-10", "Q-11", "Q-12"};
        String[] sj1 = {"S-1", "S-2", "S-3", "S-4", "S-5"};
        String[] sj2 = {"S-6", "S-7", "S-8", "S-9"};
        String[] jy1 = {"J-1", "L-1"};
        machineMap.put("sb1", sb1);
        machineMap.put("sb2", sb2);
        machineMap.put("sj1", sj1);
        machineMap.put("sj2", sj2);
        machineMap.put("jy1", jy1);
    }
}